package com.weiaibenpao.demo.chislim.retrofit.rx;


import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.retrofit.NetWorkManager;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by wlx on 2017/12/5.
 * 观察者
 */

public abstract class SimpleObserver<T> implements Observer<T> {

    private Disposable mDisposable;//资源
    private CompositeDisposable mCompositeDisposable;// CompositeDisposable 管理的 一些一次性资源

    public SimpleObserver(CompositeDisposable compositeDisposable) {
        this.mCompositeDisposable = compositeDisposable;
    }
    @Override
    public void onSubscribe(@NonNull  Disposable disposable) {
       this.mDisposable=disposable;
        if (isDisposed()){
            mCompositeDisposable.add(disposable);// 将需要被 CompositeDisposable 管理的 observer 加入到管理集合中
        }
    }
    private boolean isDisposed() {
        return mCompositeDisposable != null && !mDisposable.isDisposed() && !mCompositeDisposable.isDisposed();
    }

    @Override
    public void onNext(T t) {
        if (t!=null){
            call(t);
        }
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable throwable) {

        showErrorMsg( NetWorkErrorFactory.disposeError(throwable));
        throwable.printStackTrace();
    }

    /**
     * 默认提示
     * @param message
     */
    public   void showErrorMsg(String message){
        if (!TextUtils.isEmpty(message)){
            Logger.e("showErrorMsg："+message);
            Toast.makeText(NetWorkManager.mContext,message,Toast.LENGTH_SHORT).show();
        }
    }



    public abstract void call(T t) ;
}
